<template>
  <n-layout has-sider>
    <n-layout-sider
      bordered
      collapse-mode="width"
      :collapsed-width="64"
      :width="240"
      :native-scrollbar="false"
      class="side-nav"
    >
      <div class="logo-container">
        <h3 v-if="!collapsed">Ollama UI</h3>
        <n-button quaternary circle @click="collapsed = !collapsed">
          <template #icon>
            <n-icon><MenuFoldOutlined v-if="collapsed" /><MenuUnfoldOutlined v-else /></n-icon>
          </template>
        </n-button>
      </div>
      <n-menu
        :collapsed="collapsed"
        :collapsed-width="64"
        :collapsed-icon-size="22"
        :options="menuOptions"
        :value="activeKey"
        @update:value="handleMenuUpdate"
      />
    </n-layout-sider>

    <n-layout>
      <n-layout-header bordered class="header">
        <div class="header-content">
          <h2>{{ getPageTitle() }}</h2>
          <div class="version-info">
            版本: {{ store.version }}
          </div>
        </div>
      </n-layout-header>

      <n-layout-content class="content">
        <div v-if="activeKey === 'models'">
          <n-card title="已安装的模型" class="model-card">
            <n-data-table
              :columns="modelColumns"
              :data="store.models"
              :bordered="false"
              :pagination="{ pageSize: 10 }"
            />
          </n-card>
        </div>

        <div v-if="activeKey === 'chat'" class="chat-view">
          <n-card>
            <template #header>
              <div class="chat-header">
                <n-select
                  v-model:value="selectedModel"
                  :options="modelOptions"
                  placeholder="选择模型"
                  class="model-select"
                />
              </div>
            </template>
            <div class="chat-container">
              <div class="chat-messages" ref="messagesRef">
                <div
                  v-for="(msg, index) in messages"
                  :key="index"
                  :class="['message', msg.role]"
                >
                  {{ msg.content }}
                </div>
              </div>
              <div class="chat-input">
                <n-input
                  v-model:value="currentMessage"
                  type="textarea"
                  placeholder="输入消息..."
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  @keydown.enter.prevent="handleSend"
                />
                <n-button
                  type="primary"
                  @click="handleSend"
                  :disabled="!selectedModel || !currentMessage.trim()"
                  :loading="sending"
                >
                  发送
                </n-button>
              </div>
            </div>
          </n-card>
        </div>
      </n-layout-content>
    </n-layout>
  </n-layout>
</template>

<script setup>
import { ref, computed, onMounted, h } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useOllamaStore } from '../store'
import { OllamaAPI } from '../api/ollama'
import { 
  useMessage,
  NLayout,
  NLayoutSider,
  NLayoutHeader,
  NLayoutContent,
  NMenu,
  NCard,
  NDataTable,
  NSelect,
  NInput,
  NButton,
  NIcon
} from 'naive-ui'
import { MenuFoldOutlined, MenuUnfoldOutlined, MessageOutlined, AppstoreOutlined } from '@vicons/antd'

const router = useRouter()
const route = useRoute()
const store = useOllamaStore()
const message = useMessage()

const collapsed = ref(false)
const activeKey = ref(route.query.tab || 'models')

const menuOptions = [
  {
    label: '模型管理',
    key: 'models',
    icon: renderIcon(AppstoreOutlined)
  },
  {
    label: '对话',
    key: 'chat',
    icon: renderIcon(MessageOutlined)
  }
]

function renderIcon(icon) {
  return () => h(NIcon, null, { default: () => h(icon) })
}

function getPageTitle() {
  const menu = menuOptions.find(item => item.key === activeKey.value)
  return menu ? menu.label : ''
}

function handleMenuUpdate(key) {
  activeKey.value = key
  router.push({ query: { ...route.query, tab: key } })
}

const modelColumns = [
  {
    title: '名称',
    key: 'name',
    width: 200
  },
  {
    title: '大小',
    key: 'size',
    width: 120
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render(row) {
      return h('span', { style: { color: row.status === 'ready' ? '#18a058' : '#666' } }, 
        row.status === 'ready' ? '已就绪' : '加载中')
    }
  }
]

const selectedModel = ref('')
const currentMessage = ref('')
const messages = ref([])
const sending = ref(false)
const messagesRef = ref(null)

const modelOptions = computed(() => {
  return store.models.map(model => ({
    label: model.name,
    value: model.name
  }))
})

async function loadModels() {
  try {
    const api = new OllamaAPI(store.baseUrl)
    const response = await api.getModels()
    if (response?.models) {
      const modelsWithStatus = response.models.map(model => ({
        ...model,
        status: 'ready'
      }))
      store.setModels(modelsWithStatus)
    } else {
      throw new Error('获取模型列表失败')
    }
  } catch (error) {
    message.error(error?.message || '加载模型列表失败')
  }
}

async function handleSend() {
  if (!currentMessage.value.trim() || !selectedModel.value || sending.value) return
  
  try {
    sending.value = true
    const api = new OllamaAPI(store.baseUrl)
    
    const userMessage = currentMessage.value.trim()
    messages.value.push({
      role: 'user',
      content: userMessage
    })
    
    currentMessage.value = ''
    
    const response = await api.chat(selectedModel.value, userMessage, messages.value)
    console.log('response', response)
    if (response?.message?.content) {
      messages.value.push({
        role: 'assistant',
        content: response.message.content
      })
      
      // 滚动到底部
      // nextTick(() => {
      //   if (messagesRef.value) {
      //     messagesRef.value.scrollTop = messagesRef.value.scrollHeight
      //   }
      // })
    } else {
      throw new Error('无效的响应格式')
    }
  } catch (error) {
    message.error(error?.message || '发送消息失败')
    // 发送失败时，移除用户消息
    messages.value.pop()
  } finally {
    sending.value = false
  }
}

onMounted(() => {
  if (!store.connected) {
    message.warning('请先连接到 Ollama 服务')
    router.push('/')
    return
  }
  loadModels()
})
</script>

<style scoped>
.side-nav {
  background: #fff;
  height: 100vh;
}

.logo-container {
  height: 64px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #eee;
}

.header {
  height: 64px;
  padding: 0 24px;
  background: #fff;
}

.header-content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.content {
  padding: 24px;
  background: #f5f5f5;
  min-height: calc(100vh - 64px);
}

.model-card {
  background: #fff;
}

.chat-view {
  height: calc(100vh - 112px);
}

.chat-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.model-select {
  width: 200px;
}

.chat-container {
  height: calc(100vh - 200px);
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 16px;
}

.message {
  margin-bottom: 12px;
  padding: 12px 16px;
  border-radius: 8px;
  max-width: 80%;
  line-height: 1.5;
}

.message.user {
  background: #e8f5e9;
  margin-left: auto;
}

.message.assistant {
  background: #fff;
  border: 1px solid #e0e0e0;
}

.chat-input {
  display: flex;
  gap: 12px;
  background: #fff;
  padding: 16px;
  border-radius: 8px;
}

.chat-input .n-input {
  flex: 1;
}
</style>